package cn.wolfcode.trip.admin.filter;


import cn.wolfcode.trip.admin.util.UploadUtil;
import org.apache.commons.io.FileUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

public class ImageFilter implements Filter{


    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        //获取图片的路径
        String uri = req.getRequestURI();
        System.out.println(uri);
        //获取公共区域中的图片
        File file = new File(UploadUtil.PATH,uri);
        //判断是否存在
        if(file.exists()){
            //响应到浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            //把文件转成byte字节数组
            outputStream.write(FileUtils.readFileToByteArray(file));
        }else {
            //放行
            chain.doFilter(request,response);
        }
    }

    public void destroy() {

    }
}
